package com.shawn.example.mvvmdemo.home.ui.wx

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.fragment.app.viewModels
import androidx.lifecycle.distinctUntilChanged
import com.alibaba.android.arouter.facade.annotation.Route
import com.jetpack.mvvm.lib.base.BaseFragment
import com.jetpack.mvvm.lib.base.RouterConstant
import com.jetpack.mvvm.lib.binding.ext.viewBind
import com.shawn.example.mvvmdemo.home.databinding.FragmentWxArticlesBinding
import com.shawn.example.mvvmdemo.home.viewmodel.WXViewModel
import dagger.hilt.android.AndroidEntryPoint

@Route(path = RouterConstant.Home.PAGE_WX)
@AndroidEntryPoint
class WXFragment : BaseFragment() {
    companion object {
        private const val TAG = "WXFragment"
    }

    private val bind by viewBind<FragmentWxArticlesBinding>()
    private val vm by viewModels<WXViewModel>()
    private val fragmentList = mutableListOf<WxDetailArticleFragment>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return bind.root
    }

    override fun initView() {

    }

    override fun lazyLoad() {
        vm.getArticles()
    }

    override fun observeViewModel() {
        vm.authorListLV.distinctUntilChanged().observe(this) { authorList ->
            fragmentList.clear()
            authorList.forEach { vo ->
                fragmentList.add(WxDetailArticleFragment.getInstance(vo.id, vo.title))
            }
            bind.wxDetailViewpager.adapter = object : FragmentStatePagerAdapter(childFragmentManager) {
                override fun getCount(): Int {
                    return fragmentList.size
                }

                override fun getItem(position: Int): Fragment {
                    return fragmentList[position]
                }

                override fun getPageTitle(position: Int): CharSequence? {
                    return authorList[position].title
                }
            }
            bind.wxArticlesTabLayout.apply {
                isVisible = true
                setViewPager(bind.wxDetailViewpager)
            }
        }
    }
}